/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ee.xml;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Gabriel Bran <gbran.u@gmail.com>
 */
public class XMLManager<T> {

    private String xmlFileName;
    private Class<T> jaxbEntityType;

    private XMLManager() {
    }

    public XMLManager(String xmlFileName, Class<T> jaxbEntityType) {
        this.xmlFileName = xmlFileName;
        this.jaxbEntityType = jaxbEntityType;
    }

    public T load() throws JAXBException {
        File file = new File(xmlFileName);
        Unmarshaller jaxbUnmarshaller = JAXBContext.newInstance(this.jaxbEntityType).createUnmarshaller();
        return (T) jaxbUnmarshaller.unmarshal(file);
    }

    public void save(T t) throws JAXBException {
        File file = new File(xmlFileName);
        Marshaller jaxbMarshaller = JAXBContext.newInstance(this.jaxbEntityType).createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(t, file);
    }

    public String getXmlFileName() {
        return xmlFileName;
    }

    public void setXmlFileName(String xmlFileName) {
        this.xmlFileName = xmlFileName;
    }

    public Class<T> getJaxbEntityType() {
        return jaxbEntityType;
    }

    public void setJaxbEntityType(Class<T> jaxbEntityType) {
        this.jaxbEntityType = jaxbEntityType;
    }
}
